package com.kun.flutter_app.qrcode

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.view.View
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView
import java.io.ByteArrayOutputStream

/**
 * @author: liangkun
 * @date: 2021-04-27 16:27
 * @description:条形码工具类，fluttter需要调用
 */
class QrCodeUtil(activity: Activity, messenger: BinaryMessenger) : PlatformView, MethodChannel.MethodCallHandler {
    var methodChannel: MethodChannel? = null

    init {
        methodChannel = MethodChannel(messenger, "com.flutter.android.qrcode")
        //flutter传递参数给android原生
        methodChannel?.setMethodCallHandler(this)
    }

    @SuppressLint("WrongThread")
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "generate_barcode") {
            val code = call.argument("code") as String?
            val bitmap = createImage(code, 200, 200, null)
            val baos = ByteArrayOutputStream()
            bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, baos)
            val bytes = baos.toByteArray()
            result.success(bytes)
        }
    }

    private fun createImage(code: String?, w: Int, h: Int, logo: Bitmap?): Bitmap? {
        if (code == null) {
            return null
        }
        try {
            //条形码CODE_128
            val fomt = BarcodeFormat.CODE_128
            val matrix: BitMatrix = MultiFormatWriter().encode(code, fomt, w, h)
            val width = matrix.width
            val height = matrix.height
            val pixel = IntArray(width * height)
            for (i in 0 until height) {
                for (j in 0 until width) {
                    if (matrix[j, i]) {
                        pixel[i * width + j] = -0x1000000
                    } else {
                        pixel[i * width + j] = -0x1
                    }
                }
            }
            val bmapp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            bmapp.setPixels(pixel, 0, width, 0, 0, width, height)
            return bmapp
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }

    override fun getView(): View {
        TODO("Not yet implemented")
    }

    override fun dispose() {
        TODO("Not yet implemented")
    }
}